<template>
    <div class="notice-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>公告管理</span>
            <div>
              <el-button type="primary" @click="handleAdd">新增公告</el-button>
            </div>
          </div>
        </template>
  
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="公告标题">
            <el-input v-model="searchForm.title" placeholder="请输入公告标题" clearable />
          </el-form-item>
          <el-form-item label="公告分类">
            <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
              <el-option label="系统公告" value="system" />
              <el-option label="活动公告" value="activity" />
              <el-option label="维护公告" value="maintenance" />
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间">
            <el-date-picker
              v-model="searchForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
  
        <!-- 公告列表 -->
        <el-table :data="noticeList" v-loading="loading" border>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="标题" width="180" />
          <el-table-column prop="category" label="分类" width="120">
            <template #default="{ row }">
              <el-tag :type="getCategoryTagType(row.category)">
                {{ getCategoryText(row.category) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="封面图" width="120">
            <template #default="{ row }">
              <el-image
                v-if="row.coverImage"
                style="width: 80px; height: 50px"
                :src="row.coverImage"
                :preview-src-list="[row.coverImage]"
                fit="cover"
              />
              <span v-else>无封面</span>
            </template>
          </el-table-column>
          <el-table-column prop="publishTime" label="发布时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.publishTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 新增/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
        @closed="handleDialogClosed"
      >
        <el-form
          ref="noticeForm"
          :model="formData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="公告标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入公告标题" />
          </el-form-item>
          <el-form-item label="公告分类" prop="category">
            <el-select v-model="formData.category" placeholder="请选择分类">
              <el-option label="系统公告" value="system" />
              <el-option label="活动公告" value="activity" />
              <el-option label="维护公告" value="maintenance" />
            </el-select>
          </el-form-item>
          <el-form-item label="封面图片">
            <el-upload
              action="#"
              :limit="1"
              :show-file-list="false"
              accept="image/png, image/jpeg"
              :file-list="formData.attachments"
              :auto-upload="false"
              :on-change="handleAttachmentChange"
              :before-upload="beforeUpload"
            >
              <template #trigger>
                <div class="avatar-uploader">
                  <img v-if="formData.coverImage" :src="formData.coverImage" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </div>
              </template>
              <template #tip>
                <div class="el-upload__tip">只能上传一张封面图（JPG/PNG，小于10MB）</div>
              </template>
            </el-upload>
          </el-form-item> 
          <el-form-item label="发布时间" prop="publishTime">
            <el-date-picker
              v-model="formData.publishTime"
              type="datetime"
              placeholder="选择发布时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              placeholder="选择结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="公告内容" prop="content">
            <el-input
              v-model="formData.content"
              type="textarea"
              :rows="6"
              placeholder="请输入公告内容"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { UploadFile, UploadFiles, UploadUserFile } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue'
  import {
    getnoticeList,
    addnotice,
    updatenotice,
    deletenotice
  } from '@/api/notice'
  
  interface notice {
  id?: number
  title: string
  content: string
  category: string
  coverImage?: string
  publishTime?: Date
  endTime?: Date
  attachments?: UploadFile[] // 改为数组类型
}
  
  // 公告列表数据
  const noticeList = ref<notice[]>([])
  const loading = ref(false)
  
  // 搜索表单
  const searchForm = reactive({
    title: '',
    category: '',
    timeRange: []
  })
  
  // 分页数据
  const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
  })
  
  // 对话框相关
  const dialogVisible = ref(false)
  const dialogTitle = ref('新增公告')
  const formData = reactive<notice>({
    title: '',
    content: '',
    category: 'system'

  })
  
  // 表单验证规则
  const rules = {
    title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
    content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
    category: [{ required: true, message: '请选择公告分类', trigger: 'change' }],
    publishTime: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
    endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
  }
  
  // 获取公告列表
  const fetchnotices = async () => {
    try {
      loading.value = true
      const params = {
        pageNum: pagination.current,
        pageSize: pagination.size,
        title: searchForm.title,
        category: searchForm.category,
        startTime: searchForm.timeRange?.[0],
        endTime: searchForm.timeRange?.[1]
      }
      
      const res = await getnoticeList(params)
      noticeList.value = res.data.records
      pagination.total = res.data.total
    } catch (error) {
      ElMessage.error('获取公告列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 搜索
  const handleSearch = () => {
    pagination.current = 1
    fetchnotices()
  }
  
  // 重置搜索
  const resetSearch = () => {
    searchForm.title = ''
    searchForm.category = ''
    searchForm.timeRange = []
    handleSearch()
  }
  
  // 分页大小改变
  const handleSizeChange = (val: number) => {
    pagination.size = val
    fetchnotices()
  }
  
  // 当前页改变
  const handleCurrentChange = (val: number) => {
    pagination.current = val
    fetchnotices()
  }
const handleAttachmentChange = (file: UploadFile) => {
  // 每次只保留最新上传的文件
  formData.attachments = [file];
  
  // 生成预览URL（如果是本地文件）
  if (file.raw) {
    formData.coverImage = URL.createObjectURL(file.raw);
  } else if (file.url) {
    formData.coverImage = file.url;
  }
};
  // 新增公告
  const handleAdd = () => {
    dialogTitle.value = '新增公告'
    Object.assign(formData, {
      id: undefined,
      title: '',
      content: '',
      category: 'system',
      attachments: [],
      publishTime: '',
      endTime: '',
      coverImage: undefined
    })
    dialogVisible.value = true
  }
  
  // 编辑公告
  const handleEdit = (row: notice) => {
    dialogTitle.value = '编辑公告'
    Object.assign(formData, JSON.parse(JSON.stringify(row)))
    dialogVisible.value = true
  }
  
  // 删除公告
  const handleDelete = (row: notice) => {
    ElMessageBox.confirm('确定要删除该公告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await deletenotice(row.id!)
        ElMessage.success('删除成功')
        fetchnotices()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    }).catch(() => {})
  }
  
  // 提交表单
  const submitForm = async () => {
    try {
      const noticeForm = new FormData();
      noticeForm.append('formData', new Blob([JSON.stringify(
       {title:formData.title,
        content:formData.content,
        category:formData.category,
        publishTime:formData.publishTime,
        endTime:formData.endTime
      }
      )], { type: 'application/json' }))
      if(formData.attachments)
      formData.attachments.forEach(file => {
      if (file.raw) {
        noticeForm.append('attachments', file.raw);
      }
    });
      if (formData.id) {

        await updatenotice(noticeForm)
        ElMessage.success('更新成功')
      } else {
        await addnotice(noticeForm)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      fetchnotices()
    } catch (error) {
      ElMessage.error('操作失败')
    }
  }
  
  // 对话框关闭
  const handleDialogClosed = () => {
    ;(noticeForm.value as any)?.resetFields()
  }
  
  
  // 图片上传前校验
  const beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 10
  
    if (!isJPG) {
      ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    }
    if (!isLt2M) {
      ElMessage.error('上传图片大小不能超过 10MB!')
    }
    return isJPG && isLt2M
  }
  
  // 分类标签样式
  const getCategoryTagType = (category: string) => {
    const map: Record<string, string> = {
      system: '',
      activity: 'success',
      maintenance: 'warning'
    }
    return map[category] || ''
  }
  
  // 分类显示文本
  const getCategoryText = (category: string) => {
    const map: Record<string, string> = {
      system: '系统公告',
      activity: '活动公告',
      maintenance: '维护公告'
    }
    return map[category] || category
  }
  
  // 格式化时间
  const formatTime = (time: string) => {
    return time ? time.replace('T', ' ') : '-'
  }
  
  const noticeForm = ref()
  
  onMounted(() => {
    fetchnotices()
  })
  </script>
  
  <style scoped>
  .notice-container {
    padding: 20px;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 100px;
  }
  
  .avatar-uploader:hover {
    border-color: #409eff;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  
  .avatar {
    width: 178px;
    height: 100px;
    display: block;
  }
  </style>